const path = require('path')
const { imgUrl } = require('../config')
const multer = require('@koa/multer')
const storage = multer.diskStorage({
  destination(req, file, cb) {
    // 文件夹需要自己提前创建好
    cb(null, path.resolve(__dirname, '../../public'))
  },
  filename(req, file, cb) {
    const index = file.originalname.lastIndexOf('.')
    const fileName = file.originalname.substring(0, index);
    const ext = path.extname(file.originalname)
    cb(null, `${fileName}-${Date.now()}${ext}`)
  }
})

const upload = multer({ storage })
const Router = require('koa-router')
const router = new Router();
// 处理文件上传请求
router.post('/upload/img', upload.single('file'), async (ctx, next) => {
  const filename = ctx.file.filename;
  ctx.body = { success: true, message: '图片上传成功', data: {  src: imgUrl + filename, srcName: filename } };
});

module.exports = app => {
  app.use(router.routes())
  .use(router.allowedMethods())
}

